/**
 * @Title: ChoosePhotoActivity.java
 * @Package: com.jason.fingerprint.ui
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月26日 上午10:27:27
 * @Version: V1.0
 */
package com.jason.fingerprint.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.kymjs.aframe.ui.BindView;
import org.kymjs.aframe.ui.KJActivityManager;
import org.kymjs.aframe.ui.activity.BaseActivity;
import org.kymjs.aframe.utils.StringUtils;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.jason.fingerprint.R;
import com.jason.fingerprint.adapter.ImageFolderAdapter;
import com.jason.fingerprint.beans.ui.ImageFolderBean;
import com.jason.fingerprint.common.DataHelper;
import com.jason.fingerprint.common.FileHelper;

/**
 * @ClassName: ChoosePhotoActivity
 * @Description: 选取上传图片
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月26日 上午10:27:27
 */
@SuppressLint("HandlerLeak")
public class ChoosePhotoActivity extends BaseActivity implements OnClickListener, OnItemClickListener {

	private static final String TAG = "ChoosePhotoActivity";
	public static final String CHOOSE_PHOTO = "mCacheCheckImages";
	public static final String CHOOSE_PHOTO_COUNT = "choose_photo_count";

	private static final int REQUEST_TAKEPHOTO_OK = 100000;

	public static final String RESULT_IMAGES = "result_images";
	public static final int REQUEST_OK = 1000;
	public static final int RESULT_OK = 1001;

	private HashMap<String, List<String>> mGruopMap = new HashMap<String, List<String>>();
	private List<ImageFolderBean> list = new ArrayList<ImageFolderBean>();
	private final static int SCAN_OK = 1;
	private ProgressDialog mProgressDialog;
	private ImageFolderAdapter adapter;
	private GridView mGroupGridView;
	public static List<String> mCacheCheckImages = new ArrayList<String>();
	public static boolean mIsOne = false;//当只选取一张图片的时候，从ChoosePhotoAcitivyt返回的结果
	@BindView(id = R.id.header_back, click = true)
	private Button mBackButton;
	@BindView(id = R.id.header_complete, click = true)
	private Button mCompleteButton;
	@BindView(id = R.id.footer_takephoto, click = true)
	private Button mTakePhotoButton;
	@BindView(id = R.id.footer_preview, click = true)
	private TextView mPreviewTextView;

	@BindView(id = R.id.header_title, click = true)
	private TextView mTitleTextView;

	private File mTakePhotoFile;
	
	private static int mChooseCount = 5;//选取图片的张数，默认五张


	@Override
	public void setRootView() {
		setContentView(R.layout.activity_image_group);
	}

	@Override
	protected void initWidget() {
		super.initWidget();
		mCompleteButton.setVisibility(View.VISIBLE);
		mTitleTextView.setText("图片");
		init();
	}

	@Override
	protected void initData() {
		super.initData();
		Intent intent = getIntent();
		if (intent != null) {
			mChooseCount = intent.getIntExtra(ChoosePhotoActivity.CHOOSE_PHOTO_COUNT, 5);
			mCacheCheckImages = intent.getStringArrayListExtra("images");
		}
		if (mCacheCheckImages == null || mCacheCheckImages.isEmpty()){
			mCacheCheckImages = new ArrayList<String>();
		}
		updateDateView();
	}

	// 初始化数据
	private void init() {
		mGroupGridView = (GridView) findViewById(R.id.main_grid);
		//getImages();
		mGroupGridView.setOnItemClickListener(this);
	}

	public void updateDateView() {
		mTakePhotoButton.setClickable(true);
		mTakePhotoButton.setClickable(true);
		if (mCacheCheckImages == null || mCacheCheckImages.isEmpty()) {
			mCompleteButton.setEnabled(false);
			mPreviewTextView.setEnabled(false);
			mCompleteButton.setClickable(false);
			mPreviewTextView.setClickable(false);
			mCompleteButton.setText("完成");
			mPreviewTextView.setText("预览");
			mPreviewTextView.setTextColor(getResources().getColor(R.color.photo_font_disable_color));
		} else {
			int count = mCacheCheckImages.size();
			mCompleteButton.setEnabled(true);
			mPreviewTextView.setEnabled(true);
			mCompleteButton.setClickable(true);
			mPreviewTextView.setClickable(true);
			mCompleteButton.setText("完成(" + count + ")");
			mPreviewTextView.setText("预览(" + count + ")");
			mPreviewTextView.setTextColor(getResources().getColor(R.color.photo_font_normal_color));
			if (count == 5) {
				Toast.makeText(this, "你已经选取了5张照片", Toast.LENGTH_SHORT).show();
				mTakePhotoButton.setClickable(false);
				mTakePhotoButton.setClickable(false);
			}
		}
	}

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case SCAN_OK:
				// 关闭进度条
				mProgressDialog.dismiss();

				adapter = new ImageFolderAdapter(ChoosePhotoActivity.this, list = subGroupOfImage(mGruopMap),
						mGroupGridView);
				mGroupGridView.setAdapter(adapter);
				break;
			}
		}

	};

	/**
	 * 利用ContentProvider扫描手机中的图片，此方法在运行在子线程中
	 */
	private void getImages() {
		mGruopMap = new HashMap<String, List<String>>();
		if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			Toast.makeText(this, "暂无外部存储", Toast.LENGTH_SHORT).show();
			return;
		}

		// 显示进度条
		mProgressDialog = ProgressDialog.show(this, null, "正在加载...");

		new Thread(new Runnable() {

			@Override
			public void run() {
				Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				ContentResolver mContentResolver = ChoosePhotoActivity.this.getContentResolver();

				// 只查询jpeg和png的图片
				Cursor mCursor = mContentResolver.query(mImageUri, null, MediaStore.Images.Media.MIME_TYPE + "=? or "
						+ MediaStore.Images.Media.MIME_TYPE + "=?", new String[] { "image/jpeg", "image/png" },
						MediaStore.Images.Media.DATE_MODIFIED);

				while (mCursor.moveToNext()) {
					// 获取图片的路径
					String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));
					// 获取该图片的父路径名
					String parentName = new File(path).getParentFile().getName();

					// 根据父路径名将图片放入到mGruopMap中
					if (!mGruopMap.containsKey(parentName)) {
						List<String> chileList = new ArrayList<String>();
						chileList.add(path);
						mGruopMap.put(parentName, chileList);
					} else {
						mGruopMap.get(parentName).add(path);
					}
				}

				mCursor.close();

				// 通知Handler扫描图片完成
				mHandler.sendEmptyMessage(SCAN_OK);

			}
		}).start();

	}

	/**
	 * 组装分组界面GridView的数据源，因为我们扫描手机的时候将图片信息放在HashMap中
	 * 所以需要遍历HashMap将数据组装成List
	 * 
	 * @param mGruopMap
	 * @return
	 */
	private List<ImageFolderBean> subGroupOfImage(HashMap<String, List<String>> mGruopMap) {
		if (mGruopMap.size() == 0) {
			return null;
		}
		List<ImageFolderBean> list = new ArrayList<ImageFolderBean>();

		Iterator<Map.Entry<String, List<String>>> it = mGruopMap.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, List<String>> entry = it.next();
			ImageFolderBean mImageBean = new ImageFolderBean();
			String key = entry.getKey();
			List<String> value = entry.getValue();

			mImageBean.setFolderName(key);
			mImageBean.setImageCounts(value.size());
			mImageBean.setTopImagePath(value.get(0));// 获取该组的第一张图片
			Log.i("image", mImageBean.toString());
			list.add(mImageBean);
		}

		return list;

	}

	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.header_back:
			KJActivityManager.create().finishActivity(ChoosePhotoActivity.this);
			break;
		case R.id.header_complete:
			backChoosePhotoAtivity();
			KJActivityManager.create().finishActivity(ChoosePhotoActivity.this);
			break;
		case R.id.footer_takephoto:
			doTakePhoto();
			break;
		case R.id.footer_preview:
			Intent mIntent = new Intent(ChoosePhotoActivity.this, PreviewPhotoActivity.class);
			mIntent.putStringArrayListExtra("images", (ArrayList<String>) mCacheCheckImages);
			mIntent.putExtra("position", 0);
			startActivity(mIntent);
			break;

		default:
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		mIsOne = false;
		String folderName = list.get(arg2).getFolderName();
		List<String> childList = mGruopMap.get(folderName);

		Intent mIntent = new Intent(ChoosePhotoActivity.this, ChoosePhotoChildActivity.class);
		mIntent.putStringArrayListExtra("data", (ArrayList<String>) childList);
		mIntent.putStringArrayListExtra("mCacheCheckImages", (ArrayList<String>) mCacheCheckImages);
		mIntent.putExtra("folderName", folderName);
		mIntent.putExtra(ChoosePhotoActivity.CHOOSE_PHOTO_COUNT, mChooseCount);
		startActivityForResult(mIntent, REQUEST_OK);
	}

	@Override
	protected void onResume() {
		super.onResume();
		getImages();
		if (mIsOne){
			backChoosePhotoAtivity();
			KJActivityManager.create().finishActivity(ChoosePhotoActivity.this);
			mIsOne = false;
		}
		updateDateView();
	}

	@Override
	public void onBackPressed() {
		// backChoosePhotoAtivity();
		super.onBackPressed();
		KJActivityManager.create().finishActivity(this);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO 自动生成的方法存根
		super.onActivityResult(requestCode, resultCode, data);
		Log.i(TAG, "requestCode:" + requestCode + ",resultCode:" + resultCode);
		if (requestCode == REQUEST_OK && resultCode == 0 && data != null) {
			mCacheCheckImages = data.getStringArrayListExtra("mCacheCheckImages");
			updateDateView();
		}
		if (requestCode == REQUEST_TAKEPHOTO_OK && resultCode == -1) {
			//getImages();
			//TODO 获取最近的一条图片信息
			String path = DataHelper.getTheNewPhotoPath(ChoosePhotoActivity.this);
			Log.i(TAG, "-----onActivityResult path" + path);
			if (!StringUtils.isEmpty(path)) {
				mCacheCheckImages.add(path);
			}
			updateDateView();
			if (mTakePhotoFile != null) {
				
			}else {
				Toast.makeText(this, "获取图片失败", Toast.LENGTH_SHORT).show();
			}
		}
	}

	// 返回调用的Activity数据
	private void backChoosePhotoAtivity() {
		Intent mIntent = new Intent();
		mIntent.putStringArrayListExtra("mCacheCheckImages", (ArrayList<String>) mCacheCheckImages);
		setResult(RESULT_OK, mIntent);
	}

	// 获取拍照
	public void doTakePhoto() {
		mTakePhotoFile = FileHelper.getPhotoFile(this);
		ContentValues values = new ContentValues();
		values.put(Media.TITLE, mTakePhotoFile.getName());
		values.put(Media.DESCRIPTION, "Image from Android Emulator");
		values.put(Media.DATA, mTakePhotoFile.getPath());
		//Uri photoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		//intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
		startActivityForResult(intent, REQUEST_TAKEPHOTO_OK);
	}

}
